import 'dart:async';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:compassx/compassx.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cjadsdk_plugin/flutter_cjadsdk_plugin.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zhibao_flutter/test/age_calculator_page.dart';
import 'package:zhibao_flutter/test/angle_detection_page.dart';
import 'package:zhibao_flutter/test/unit_convertion_page.dart';
import 'package:zhibao_flutter/util/config/page_util.dart';
import 'package:zhibao_flutter/util/data/actions.dart';
import 'package:zhibao_flutter/util/data/notice.dart';
import 'package:zhibao_flutter/util/http/env.dart';
import 'package:zhibao_flutter/widget/appbar/commom_bar.dart';
import 'package:zhibao_flutter/widget/base/my_scaffold.dart';
import 'package:zhibao_flutter/widget/dialog/confirm_dialog.dart';
import 'package:zhibao_flutter/zone.dart';

import 'home_logic.dart';

class HomePage extends StatelessWidget {
  final RxInt currentIndex;

  HomePage(this.currentIndex);

  final logic = Get.find<HomeLogic>();

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeLogic>(builder: (logic) {
      final itemWidth = 346.px;
      final itemHeight = 158.px;

      Widget imgBannerShow(BuildContext context, int index) {
        return Container(
          padding: EdgeInsets.symmetric(horizontal: ((375 - 346) / 2).px),
          height: itemHeight,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.px),
            child: Q1Data.hideMode.not()
                ? CachedNetworkImage(
                    imageUrl:
                        "${Environment.current}adpic/preview?path=${logic.bannerList[index].picUrl}",
                    fit: BoxFit.cover,
                    width: itemWidth,
                    height: itemHeight,
                  )
                : Stack(
                    alignment: Alignment.center,
                    children: [
                      Image.asset(
                        "assets/images/main/banner_backgroud.jpg",
                        fit: BoxFit.cover,
                        width: itemWidth,
                        height: itemHeight,
                      ),
                      Text(
                        '${AppConfig.appName}${"isHere".tr}',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 30.px,
                            fontWeight: FontWeight.w600),
                      )
                    ],
                  ),
          ),
        );
      }

      return Obx(
        () => MyScaffold(
          checkDoubleExit: currentIndex.value == 0,
          body: ListView(
            padding: EdgeInsets.all(0),
            children: [
              Obx(
                () => Container(
                  height: logic.bannerList.isNotEmpty ? (171 + 83).px : 100.px,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Color(0xffF37135),
                        Color(0xffF37135).withOpacity(0),
                      ],
                    ),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height: FrameSize.padTopH()),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: 60.px,
                            height: 60.px,
                          ),
                          Text(
                            'home'.tr,
                            style: TextStyle(
                              color: Color(0xff171616),
                              fontSize: 16.px,
                              fontWeight: MyFontWeight.medium,
                            ),
                          ),
                          SizedBox(
                            width: 60.px,
                            height: 60.px,

                            /// Second 2024/02/21
                            /// 直接砍掉,  不做扫码
                            // child: IconButton(
                            //   onPressed: () {
                            //     Get.to(QRViewExample());
                            //   },
                            //   icon: Icon(CupertinoIcons.qrcode_viewfinder),
                            // ),
                          )
                        ],
                      ),
                      // SizedBox(height: (28 - 12).px),
                      Spacer(),
                      () {
                        if (logic.bannerList.isEmpty) {
                          return Container();
                        }
                        return Container(
                          width: FrameSize.winWidth(),
                          height: itemHeight,
                          child: logic.bannerList.length == 1
                              ? InkWell(
                                  onTap: () async {
                                    PageUtil.toDefWebViewPage();
                                  },
                                  child: imgBannerShow(context, 0),
                                )
                              : Swiper(
                                  itemCount: logic.bannerList.length,
                                  onTap: (index) async {
                                    PageUtil.toDefWebViewPage();
                                  },
                                  itemBuilder: imgBannerShow,
                                ),
                        );
                      }(),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 14.px),
              if (Q1Data.hideMode.not())
                SizedBox(
                  height: 82.px,
                  width: FrameSize.winWidth(),
                  child: CupertinoScrollbar(
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      children: List.generate(
                        logic.mockColumn.length,
                        (index) {
                          return InkwellWithOutColor(
                            child: Container(
                              margin: EdgeInsets.only(
                                  right: 25.px, left: index == 0 ? 16.px : 0),
                              child: Column(
                                children: [
                                  ClipRRect(
                                    child: Image.asset(
                                      "assets/images/home_mock/home_mock_row_${index + 1}.png",
                                      width: 42.px,
                                      height: 42.px,
                                      fit: BoxFit.cover,
                                    ),
                                    // child: CachedNetworkImage(
                                    //   imageUrl:
                                    //       "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
                                    //   width: 42.px,
                                    //   height: 42.px,
                                    //   fit: BoxFit.cover,
                                    // ),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(10.px),
                                    ),
                                  ),
                                  Expanded(
                                    child: Center(
                                      child: Text(
                                        logic.mockColumn[index],
                                        style: TextStyle(
                                          color: Color(0xff171616),
                                          fontSize: 14.px,
                                          fontWeight: MyFontWeight.medium,
                                        ),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            onTap: () {
                              if (logic.mockColumn[index] == "短剧") {
                                PageUtil.toShortPlayDetail();
                              } else if (logic.mockColumn[index] == "游戏") {
                                PageUtil.toGame();
                              } else if (logic.mockColumn[index] == "话费" ||
                                  logic.mockColumn[index] == "充话费") {
                                PageUtil.toRechargeBalance();
                              } else {
                                /// 【Mar 28 2024】
                                /// 下单【五大板块】
                                PageUtil.toOrder();
                                // PageUtil.toDefWebViewPage();
                              }
                            },
                          );
                        },
                      ),
                    ),
                  ),
                ),
              SizedBox(height: 10.px),
              Obx(() {
                if (logic.noticeText.value.isEmpty) {
                  return Container();
                }
                final noticeGet = Q1Data.hideMode.not()
                    ? logic.noticeText.value
                    : "supportThanks".tr;
                return InkwellWithOutColor(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 10.px),
                      margin: EdgeInsets.only(bottom: 10.px),
                      child: Card(
                        child: Container(
                          margin: EdgeInsets.symmetric(horizontal: 10.px),
                          height: 40.px,
                          width: FrameSize.winWidth(),
                          child: Row(
                            children: [
                              Text('announcement'.tr),
                              Expanded(
                                child: YYMarquee(
                                  stepOffset: 200.0,
                                  duration: Duration(seconds: 5),
                                  paddingLeft: 150.0,
                                  children: [
                                    Text(
                                      noticeGet,
                                      style: TextStyle(
                                        fontSize: 13.px,
                                        color: Color(0xFFEE8E2B),
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    onTap: () {
                      confirmDialog(Get.context!, text: noticeGet);
                    });
              }),
              SizedBox(
                height: 50.px,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: logic.tabList.length,
                  itemBuilder: (context, index) {
                    final e = logic.tabList[index];
                    return InkwellWithOutColor(
                      child: Container(
                        padding: EdgeInsets.only(left: 16.px, right: 16.px),
                        margin: EdgeInsets.only(top: 20.px, bottom: 10.px),
                        decoration: BoxDecoration(
                          border: Border(
                            right: BorderSide(
                              color: Color(0xff000000).withOpacity(
                                  index == (logic.tabList.length - 1)
                                      ? 0
                                      : 0.1),
                              width: 1.px,
                            ),
                          ),
                        ),
                        alignment: Alignment.center,
                        child: Obx(() {
                          final select = logic.currentIndex.value == index;
                          return Text(
                            e,
                            style: TextStyle(
                              color: select
                                  ? Color(0xff171616)
                                  : Color(0xff171616),
                              fontSize: 12.px,
                              fontWeight: select
                                  ? MyFontWeight.semBold
                                  : MyFontWeight.medium,
                            ),
                          );
                        }),
                      ),
                      onTap: () {
                        logic.changeTab(index);
                      },
                    );
                  },
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: ((16 + 13) / 2).px),
                child: Obx(() {
                  final tabStr = logic.tabList[logic.currentIndex.value];
                  final useList = logic.mainContent[tabStr];
                  final useKey = logic.tabKeyList[logic.currentIndex.value];

                  return Wrap(
                    spacing: 8.px,
                    runSpacing: 8.px,
                    children: List.generate(
                      useList.length,
                      (index) {
                        final childItemStr = useList[index];
                        return InkwellWithOutColor(
                          child: Container(
                            width: 169.px,
                            padding:
                                EdgeInsets.all(8.px).copyWith(bottom: 0.px),
                            decoration: BoxDecoration(
                              boxShadow: MyTheme.mainShadow,
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4.px)),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                if (Q1Data.hideMode)
                                  Container(
                                    width: 153.px,
                                    height: 113.px,
                                    decoration: BoxDecoration(
                                      color:
                                          MyTheme.themeColor().withOpacity(0.8),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(10.px)),
                                    ),
                                    alignment: Alignment.center,
                                    child: Text(
                                      childItemStr,
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                if (Q1Data.hideMode.not())
                                  Stack(
                                    children: [
                                      SwImage(
                                        "assets/images/home_mock/$useKey${index + 1}.png",
                                        width: 153.px,
                                        height: 113.px,
                                        fit: BoxFit.cover,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(2.px)),
                                      ),
                                      // SwImage(
                                      //   "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
                                      //   width: 153.px,
                                      //   height: 113.px,
                                      //   fit: BoxFit.cover,
                                      //   borderRadius:
                                      //       BorderRadius.all(Radius.circular(2.px)),
                                      // ),
                                      Positioned(
                                        bottom: 0.px,
                                        left: 0.px,
                                        right: 0.px,
                                        child: Container(
                                          height: 22.px,
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 4.px),
                                          decoration: BoxDecoration(
                                            gradient: LinearGradient(
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter,
                                              colors: [
                                                Color(0xff000000)
                                                    .withOpacity(0),
                                                Color(0xff000000)
                                                    .withOpacity(0.6),
                                              ],
                                            ),
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(2.px)),
                                          ),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              SvgPicture.asset(
                                                'assets/images/home/home_item_white_column.svg',
                                                width: 10.px,
                                              ),
                                              SizedBox(width: 2.px),
                                              Expanded(
                                                child: Text(
                                                  formatNumberInDifLan(
                                                      901.2 * 10000),
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 8.px,
                                                  ),
                                                ),
                                              ),
                                              Text(
                                                // '更新至21集',
                                                '',
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 8.px),
                                              )
                                            ],
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                SizedBox(height: 4.px),
                                Text(
                                  childItemStr,
                                  style: TextStyle(
                                    color: Color(0xff171616),
                                    fontSize: 12.px,
                                    fontWeight: MyFontWeight.medium,
                                  ),
                                ),
                                SizedBox(height: 5.px),
                              ],
                            ),
                          ),
                          onTap: () {
                            print(
                                "tabStr::$tabStr, useKey::$useKey, childItemStr::$childItemStr");
                            if (tabStr == "日常工具") {
                              if (childItemStr == "历史上的今天") {
                                Get.toNamed(RouteConfig.webViewPage,
                                    arguments: {
                                      "linkUrl": "http://m.todayonhistory.com/",
                                    });
                              } else if (childItemStr == "热搜榜单") {
                                Get.toNamed(RouteConfig.webViewPage,
                                    arguments: {
                                      "linkUrl":
                                          "https://s.weibo.com/top/summary?cate=realtimehot",
                                    });
                              } else if (childItemStr == "角度检测") {
                                Get.to(AngleDetectionPage());
                              } else {
                                showToast("comingSoon".tr);
                              }
                            } else if (tabStr == "查询工具") {
                              if (childItemStr == "单位换算") {
                                Get.to(UnitConversionPage());
                              } else if (childItemStr == "年龄计算器") {
                                Get.to(AgeCalculatorPage());
                              } else {
                                showToast("comingSoon".tr);
                              }
                            } else {
                              /// 【Mar 28 2024】
                              /// 下单【五大板块】
                              PageUtil.toOrder();
                            }

                            // if (logic.currentIndex.value == 1) {
                            //   PageUtil.toShortPlayDetail();
                            // } else if (logic.currentIndex.value == 2) {
                            //   PageUtil.toGame();
                            // } else if (logic.currentIndex.value == 3) {
                            //   PageUtil.toRechargeBalance();
                            // } else {
                            //   PageUtil.toDefWebViewPage();
                            // }
                          },
                        );
                      },
                    ),
                  );
                }),
              ),
              SizedBox(height: 20.px),
            ],
          ),
        ),
      );
    });
  }
}

class YYMarquee extends StatefulWidget {
  Duration duration; // 轮播时间
  double stepOffset; // 偏移量
  double paddingLeft; // 内容之间的间距
  List<Widget> children = []; //内容
  YYMarquee(
      {required this.paddingLeft,
      required this.duration,
      required this.stepOffset,
      required this.children});

  _YYMarqueeState createState() => _YYMarqueeState();
}

class _YYMarqueeState extends State<YYMarquee> {
  ScrollController? _controller; // 执行动画的controller
  Timer? _timer; // 定时器timer
  double _offset = 0.0; // 执行动画的偏移量

  @override
  void initState() {
    super.initState();

    _controller = ScrollController(initialScrollOffset: _offset);
    _timer = Timer.periodic(widget.duration, (timer) {
      double newOffset = _controller!.offset + widget.stepOffset;
      if (newOffset != _offset) {
        _offset = newOffset;
        _controller?.animateTo(_offset,
            duration: widget.duration, curve: Curves.linear); // 线性曲线动画
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _controller?.dispose();
    super.dispose();
  }

  Widget _child() {
    return new Row(children: _children());
  }

  // 子视图
  List<Widget> _children() {
    List<Widget> items = [];
    List list = widget.children;
    for (var i = 0; i < list.length; i++) {
      Container item = new Container(
        margin: new EdgeInsets.only(right: widget.paddingLeft),
        child: list[i],
      );
      items.add(item);
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      scrollDirection: Axis.horizontal, // 横向滚动
      controller: _controller, // 滚动的controller
      itemBuilder: (context, index) {
        return _child();
      },
    );
  }
}
